﻿<template>
  <div class="nav-page">
    <!-- 右上角管理入口按钮 -->
    <div class="admin-btn" title="考试管理">
      <el-button :icon="Setting" circle @click="goAdmin" />
    </div>
    <div class="container-card">
      <div class="header">
        <h1 class="title">在线考试系统</h1>
        <p class="desc">查看可参加考试、开始考试、历史考试与错题练习</p>
      </div>

      <div class="section">
        <div class="section-header">
          <span class="section-title">可参加考试列表</span>
          <button class="btn" @click="loadAvailable">加载列表</button>
        </div>
        <ul class="list-items">
          <li v-for="p in availableExams" :key="p.id" class="list-item">
            <span class="text">{{ p.name }}（{{ p.durationMinutes }}分钟 / 总分 {{ p.totalScore }}）</span>
            <button class="btn" @click="start(p.id)">开始考试</button>
          </li>
        </ul>
      </div>

      <div class="section">
        <div class="section-header">
          <span class="section-title">我的历史考试</span>
          <div class="inline">
            <button class="btn" @click="loadMyAttempts">加载列表</button>
          </div>
        </div>
        <ul class="list-items">
          <li v-for="a in myAttempts" :key="a.id" class="list-item">
            <span class="text">{{ a.examPaper && a.examPaper.name ? a.examPaper.name : a.paperId }} | 总分 {{ a.totalScore
              != null ? a.totalScore : 0 }}分 | {{ a.status === 2 ? '已结束' : '考试中' }}</span>
            <button class="btn" @click="loadAttemptDetail(a.id)">详情</button>
          </li>
        </ul>
        <div class="pager">
          <el-pagination v-model:current-page="attemptPageNum" v-model:page-size="attemptPageSize"
            :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="attemptTotal"
            @current-change="onAttemptPageChange" @size-change="onAttemptSizeChange" />
        </div>
        <div v-if="attemptDetail" class="detail-box">
          <div class="section-subtitle">考试详情</div>
          <pre class="pre">{{ attemptDetail }}</pre>
        </div>
      </div>

    </div>
  </div>

</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import {
  getAvailableExams,
  startExam,
  getMyAttempts,
  getAttemptDetail,
  practiceWrongBook,
} from '@/api/exam/exam'

const availableExams = ref<any[]>([])
const myAttempts = ref<any[]>([])
const attemptDetail = ref<any | null>(null)
const practiceList = ref<any[]>([])
const router = useRouter()

// 默认用户ID，可按实际登录用户替换
const userId = ref<number>(0)
const tagId = ref<number | undefined>(undefined)

// 从本地存储初始化用户信息
function initUserFromStorage() {
  try {
    const raw = localStorage.getItem('sysUser')
    if (!raw) return
    const obj = JSON.parse(raw)
    // 保存时可能是 res.data.data 或 res.data，这里做兼容
    const data = obj && typeof obj === 'object' && obj.data && typeof obj.data === 'object' ? obj.data : obj
    const uid = Number(data?.id ?? data?.userId ?? data?.uid)
    if (Number.isFinite(uid) && uid > 0) {
      userId.value = uid
    }
    const tid = Number(data?.tagId ?? data?.currentTagId ?? data?.groupId)
    if (Number.isFinite(tid) && tid > 0) {
      tagId.value = tid
    }
  } catch (e) {
    // ignore parse errors silently
  }
}
const practiceLimit = ref<number | undefined>(10)
// 历史考试分页状态
const attemptPageNum = ref<number>(1)
const attemptPageSize = ref<number>(10)
const attemptTotal = ref<number>(0)

async function loadAvailable() {
  try {
    const { data } = await getAvailableExams()
    availableExams.value = data?.data || []
    if (!availableExams.value.length) {
      ElMessage({ type: 'warning', message: '当前暂无可参加考试' })
    }
  } catch (e) {
    // 错误在拦截器内处理
  }
}

async function start(paperId: number) {
  try {
    if (userId.value === 0) {
      initUserFromStorage()
    }
    const { data } = await startExam(paperId, { userId: userId.value, deviceInfo: 'Web/Windows' })
    const attemptId = data?.data
    ElMessage({ type: 'success', message: `考试已开始，attemptId=${attemptId}` })
    // 跳转到作答页面（不显示正确答案、无删除按钮，可点击选项）
    router.push({ name: 'examDo', params: { paperId }, query: { attemptId: attemptId ?? '' } })
  } catch (e) { }
}

async function loadMyAttempts() {
  try {
    const { data } = await getMyAttempts({ userId: userId.value, page: attemptPageNum.value, size: attemptPageSize.value })
    const body = data?.data
    if (body && typeof body === 'object' && Array.isArray(body.list)) {
      myAttempts.value = body.list
      attemptTotal.value = Number(body.total ?? body.list?.length ?? 0)
      attemptPageNum.value = Number(body.pageNum ?? body.page ?? attemptPageNum.value)
      attemptPageSize.value = Number(body.pageSize ?? body.size ?? attemptPageSize.value)
    } else if (Array.isArray(body)) {
      myAttempts.value = body
      attemptTotal.value = body.length
    } else {
      myAttempts.value = []
      attemptTotal.value = 0
    }
    attemptDetail.value = null
    console.log('myAttempts', myAttempts.value)
  } catch (e) { }
}

async function loadAttemptDetail(id: number) {
  router.push(`/examAttempt/${id}`)
}

async function loadPractice() {
  try {
    const { data } = await practiceWrongBook({ userId: userId.value, tagId: tagId.value, limit: practiceLimit.value })
    practiceList.value = data?.data || []
  } catch (e) { }
}

// 跳转到考试管理页面
function goAdmin() {
  router.push('/examAdmin')
}

function onAttemptPageChange(page: number) {
  attemptPageNum.value = page
  loadMyAttempts()
}

function onAttemptSizeChange(size: number) {
  attemptPageSize.value = size
  attemptPageNum.value = 1
  loadMyAttempts()
}

// 页面启动自动加载可参加考试和我的历史考试
onMounted(() => {
  // 先初始化本地用户，再加载数据
  initUserFromStorage()
  loadAvailable()
  loadMyAttempts()
})
</script>

<style scoped>
.nav-page {
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  background: #f5f7fb;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 右上角浮动按钮 */
.admin-btn {
  position: fixed;
  top: 14px;
  right: 14px;
  z-index: 1000;
}

.container-card {
  max-width: 1060px;
  margin: 0 auto;
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 20px;
  box-shadow: 0 10px 24px rgba(31, 45, 61, 0.06);
  padding-top: 28px;
  padding-bottom: 28px;
  padding-left: 100px;
  padding-right: 100px;
}

.header {
  margin-bottom: 16px;
}

.title {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
}

.desc {
  margin-top: 6px;
  color: #6b7280;
}

.section {
  margin-top: 18px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.section-title {
  font-weight: 700;
  color: #1f2937;
}

.section-subtitle {
  margin: 8px 0;
  color: #374151;
  font-weight: 600;
}

.inline {
  display: flex;
  gap: 8px;
  align-items: center;
}

.btn {
  border: 1px solid #e5e7eb;
  background: #fff;
  border-radius: 8px;
  padding: 6px 10px;
  color: #374151;
  cursor: pointer;
}

.btn:hover {
  background: #f9fafb;
}

.input {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 6px 10px;
}

.list-items {
  list-style: none;
  padding: 0;
  margin: 0;
}

.list-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: 12px 14px;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  margin-bottom: 10px;
  background: #fafafa;
}

.text {
  color: #1f2937;
}

.pre {
  white-space: pre-wrap;
  background: #f9fafb;
  border: 1px dashed #e5e7eb;
  border-radius: 8px;
  padding: 10px;
}

.detail-box {
  border-top: 1px dashed #e5e7eb;
  padding-top: 8px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

@media (max-width: 720px) {
  .container-card {
    padding-left: 16px;
    padding-right: 16px;
  }
}
</style>
